<?php
/**
 * 快找设计师助手对话控制器
 */
namespace Beerus\Modules\DesignerFinder\Controllers;

use App\Http\Controllers\Controller;
use Doraemon\model\DesignerCompetition\DesignerAward;
use Doraemon\model\DesignerCompetition\DesignerAwardSign2020;
use Doraemon\model\DesignerFinder\VirtualDialogue;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Widgets\Form;
use Illuminate\Http\Request;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use App\Pockets\GridDataModel as pGridDataModel;
use Encore\Admin\Widgets\Tab;
use Illuminate\Support\MessageBag;

class DialogueController extends Controller
{

    const PAGE_SIZE = 10;

    public function __construct()
    {
        parent::__construct();
        Admin::script('$(".pjax-container").attr("id","pjax-container");');
    }

    // 对话列表
    public function index(Request $request, Content $content)
    {
        $page_size = $request->input("per_page", self::PAGE_SIZE);
        $page = $request->input("page", 1);

        $condition = [];
        if (!empty($request['dialogue_id'])) {
            $condition['dialogue_id'] = $request['dialogue_id'];
        }
        if (!empty($request['dialogue_tag'])) {
            $condition['dialogue_tag'] = $request['dialogue_tag'];
        }
        if (!empty($request['dialogue_sort'])) {
            $condition['dialogue_sort'] = $request['dialogue_sort'];
        }
        if (array_key_exists($request['is_question'], VirtualDialogue::IS_QUESTION_POOL)) {
            $condition['is_question'] = $request['is_question'];
        }

        $condition['dialogue_status'] = VirtualDialogue::STATUS_NORMAL;
        $total = VirtualDialogue::count($condition);
        $condition['ORDER'] = ['id' => 'DESC'];
        $condition['LIMIT'] = [
            ($page - 1) * $page_size,
            $page_size
        ];
        $lists = VirtualDialogue::select('*', $condition);

        $gridModel = new pGridDataModel($lists, $total, [
            'perPage' => $page_size
        ]);

        $search_params = http_build_query($condition);
        $gridList = Admin::grid(
            $gridModel,
            function (Grid $grid) use ($gridModel, $search_params) {
                $grid->setActionClass(DropdownActions::class);
                $grid->paginate($gridModel->getPerPage());
                $grid->disableExport();
                $grid->disableRowSelector();

                $grid->filter(function (Grid\Filter $filter) {
                    $filter->disableIdFilter();
                    $filter->column(1 / 2, function ($filter) {
                        $filter->equal('dialogue_id', '对话ID')->placeholder('请输入对话ID');
                    });
                    $filter->column(1 / 2, function ($filter) {
                        $filter->equal('dialogue_tag', '对话标签')->select(VirtualDialogue::ALL_TAGS);
                    });
                    $filter->column(1 / 2, function ($filter) {
                        $filter->equal('dialogue_sort', '对话顺序')->placeholder('请输入对话顺序');
                    });
                    $filter->column(1 / 2, function ($filter) {
                        $filter->equal('is_question', '是否是问题')->select(VirtualDialogue::IS_QUESTION_POOL);
                    });
                    $filter->expand();
                });

                $grid->column('dialogue_id', '对话ID');
                $grid->column('dialogue_tag', '对话标签')->display(function() {
                    return VirtualDialogue::ALL_TAGS[$this->dialogue_tag];
                });
                $grid->column('dialogue_content', '对话内容');
                $grid->column('dialogue_sort', '对话顺序');
                $grid->column('is_question', '是否是问题')->display(function () {
                    return VirtualDialogue::IS_QUESTION_POOL[$this->is_question];
                });
                $grid->column('is_match_last', '是否是匹配的最后一个')->display(function () {
                    return VirtualDialogue::IS_QUESTION_POOL[$this->is_match_last];
                });
                $grid->actions(function (Grid\Displayers\Actions $actions) {

                });
            }
        );

        $tab = new Tab();
        $tab->add('虚拟对话列表', $gridList->render());
        $content->row($tab);
        return $content
            ->header('虚拟对话列表')
            ->description(' ')
            ->breadcrumb(['text' => '虚拟对话列表']);
    }

    // 新增/修改奖项信息
    public function edit(Request $request, Content $content, $id = 0) {
        $request = $request->all();

        if (!$id) {
            $is_create = true;
            $header = '新增';
        } else {
            $is_create = false;
            $header = '修改';
        }

        $tab = new Tab();
        $tab->add('对话信息', self::editAction($request, $id, $is_create));
        return $content->header($header)
            ->breadcrumb([
                'text' => '虚拟对话列表',
                'url' => route('dialogue.list')
            ], ['text' => $header])->row($tab);
    }

    public function editAction($request, $id = 0, $isCreate = false)
    {
        if ($isCreate) {
            $data = [];
            $form = new Form($data);
        } else {
            $data = VirtualDialogue::get('*', ['id' => $id]);
            $form = new Form($data);
            $form->text('dialogue_id', '对话ID')->setWidth(4, 2)->readOnly();
        }

        $form->select('dialogue_tag', '对话标签')
            ->setWidth(4, 2)
            ->options(VirtualDialogue::ALL_TAGS)
            ->required('必选')
            ->help('除了开场白标签，其余均唯一');
        $form->text('dialogue_content', '对话内容')
            ->setWidth(4, 2)
            ->required('不能为空')
            ->help('当为"带微信号消息"时，微信号用 ' . VirtualDialogue::WITH_WECHAT_ID_FLAG . ' 符号占位代替');
        $form->text('dialogue_sort', '对话顺序')
            ->setWidth(4, 2)
            ->required('不能为空')
            ->help('数字越大，排序越靠后；房屋信息卡片及之后的标签对话顺序需大于999');
        $form->select('is_question', '是否是问题')
            ->setWidth(4, 2)
            ->options(VirtualDialogue::IS_QUESTION_POOL)
            ->default(VirtualDialogue::QUESTION_YES)
            ->help('是问题的是需要用户回答的');
        $form->select('is_match_last', '是否是最后一个')
            ->setWidth(4, 2)
            ->options(VirtualDialogue::IS_MATCH_LAST_POOL)
            ->default(VirtualDialogue::MATCH_LAST_NO)
            ->help('指的是是否是匹配设计师需要填写的最后一个问题');

        $form->action('/admin/DesignerFinder/dialogue/save');
        return $form->render();
    }

    // 编辑奖项
    public function editSubmit(Request $request)
    {
        $request = $request->all();
        $data = [
            'dialogue_tag' => $request['dialogue_tag'],
            'dialogue_content' => $request['dialogue_content'],
            'dialogue_sort' => $request['dialogue_sort'],
            'is_question' => $request['is_question'],
            'is_match_last' => $request['is_match_last'],
        ];
        if (!$this->checkParams($request['dialogue_id'], 'dialogue_tag', $request['dialogue_tag'])) {
            $error = new MessageBag(['title' => '已经存在该标签的对话']);
            return back()->with(compact('error'));
        }
        if (!$this->checkParams($request['dialogue_id'], 'dialogue_content', $request['dialogue_content'])) {
            $error = new MessageBag(['title' => '已经存在该内容的对话']);
            return back()->with(compact('error'));
        }
        if (!$this->checkParams($request['dialogue_id'], 'dialogue_sort', $request['dialogue_sort'])) {
            $error = new MessageBag(['title' => '已经存在该顺序的对话']);
            return back()->with(compact('error'));
        }
        if (!$this->checkParams($request['dialogue_id'], 'is_match_last', $request['is_match_last'])) {
            $error = new MessageBag(['title' => '已经存在匹配设计师之前填的对话']);
            return back()->with(compact('error'));
        }
        if (in_array($request['dialogue_tag'], VirtualDialogue::BIG_SORT_TAGS) && $request['dialogue_sort'] <= 999) {
            $error = new MessageBag(['title' => '该标签的对话顺序需大于999']);
            return back()->with(compact('error'));
        }
        if ($request['is_match_last'] == VirtualDialogue::MATCH_LAST_YES && !in_array($request['dialogue_tag'], VirtualDialogue::MATCH_DESIGNER_DIALOGUE_TAGS)) {
            $error = new MessageBag(['title' => '是否是匹配设计师最后一个问题不在指定范围标签中']);
            return back()->with(compact('error'));
        }
        if ($request['dialogue_tag'] == VirtualDialogue::WECHAT_ID_INFO_TAG && mb_strpos($request['dialogue_content'], VirtualDialogue::WITH_WECHAT_ID_FLAG) === false) {
            $error = new MessageBag(['title' => '需要带微信号占位符']);
            return back()->with(compact('error'));
        }
        if (isset($request['dialogue_id'])) {
            $rs = VirtualDialogue::updateDialogueById($data, $request['dialogue_id']);
        } else {
            $id = microtime();
            $data['dialogue_id'] = substr($id, 11) . substr($id, 2, 6);
            $rs = VirtualDialogue::createDialogue($data);
        }
        $title = isset($request['dialogue_id']) ? '修改成功' : '添加成功';
        if (!$rs) {
            $error = new MessageBag(['title' => $title]);
            return back()->with(compact('error'));
        }
        $success = new MessageBag(['title' => $title]);
        return redirect('/admin/DesignerFinder/dialogue')->with(compact('success'));
    }

    public function checkParams($dialogue_id, $tag, $param) {
        $flag = true;
        switch ($tag) {
            case 'dialogue_tag':
                $dialogue = VirtualDialogue::getDialogueByTag($param);
                break;
            case 'dialogue_content':
                $dialogue = VirtualDialogue::getDialogueByContent($param);
                break;
            case 'dialogue_sort':
                $dialogue = VirtualDialogue::getDialogueBySort($param);
                break;
            case 'is_match_last':
                $dialogue = VirtualDialogue::getDialogueByIsMatch();
                $flag = ($param == VirtualDialogue::STATUS_NORMAL ? true : false);
                break;
            default :
                return false;
        }
        if ($flag && ($dialogue_id
                && $dialogue
                && $dialogue['dialogue_id'] != $dialogue_id) ||
            (!$dialogue_id && $dialogue)) {
            return false;
        }
        return true;
    }

    // 删除奖项
    public function delDialogue($id) {
        $dialogue = VirtualDialogue::getDialogueById($id);
        if ($dialogue) {
            $data['dialogue_status'] = VirtualDialogue::STATUS_DELETE;
            $data['edit_time'] = time();
            $rs = VirtualDialogue::update($data, ['id' => $id]);
            if ($rs) {
                return response()->json([
                    'status' => true,
                    'message' => "操作成功",
                ]);
            }
        }
        return response()->json([
            'status' => false,
            'message' => "操作失败",
        ]);
    }
}
